<template>
  <div style="height: 100%">
  </div>
</template>

<script>
  import Format from '@/utils/format'

  export default {
    // type  AB  AO  BO
    props: {
      type: {
        type: String,
        default: '',
      },
      xNum: {
        type: Number,
        default: 100,
      }
    },
    data() {
      return {
        markAreas: {},
        charts: '',
        yList: [],
        yList2: [],
        timerList: [],
        seriesList: [{
          itemStyle: {
            normal: {
              lineStyle: {
                width: 63//设置线条粗细
              }
            }
          }
        }],
        monitorName: '',
      }
    },
    computed: {
      user() {
        return this.$store.state.userInfo
      },
      yName() {
        return this.type === 'X' || this.type === 'Y' ? '角度(°)' : '位移(mm)'
      },
      options() {
        var _this = this
        function formatter(params) {
          var contentArr = []
          for (var i = 0; i < params.length; i++) {

            var data = params[i]
            if (i === 0) {
              contentArr.push('孔深：' + -data.value[1] + 'm')
            }
            let y = String(data.value).indexOf(".") + 1;//获取小数点的位置
            let count = String(data.value).length - y;//获取小数点后的个数
            if (_this.type == 'X' || _this.type == 'Y' || _this.type == 'az' || _this.type == 'in') {
              if (data.value !== undefined) {
                if (count < 3) {
                  contentArr.push(data.marker + data.seriesName + '：' + data.value[0] + '°')
                } else {
                  contentArr.push(data.marker + data.seriesName + '：' + data.value[0].toFixed(3) + '°')
                }
              }


            } else {
              contentArr.push(data.marker + data.seriesName + '：' + data.value[0].toFixed(3) + 'mm')
            }
          }
          // contentArr.push("<i style='font-size:10px' >提示：点击查看时间位移曲线</i>")
          return contentArr.join('<br/>')
        }

        return {
          title: {
            text: `${this.monitorName}`,
            x: 'center'
          },
          dataZoom: [

            {
              // X轴的滚动条
              type: 'slider',
              show: true,
              xAxisIndex: [0],
              bottom: '0%', // 根据实际情况调整位置
              start: -100,
              end: 100 // 根据实际情况调整显示范围
            },
            {
              // 内置的X轴缩放，可以用鼠标滚轮操作
              type: 'inside',
              xAxisIndex: [0],
            }
          ],
          animationDuration: 2000, // 动画时长 可以接受 回调函数
          //提示框组件
          tooltip: {
            position: ['10', '10'],
            // 设置为坐标轴触发
            trigger: 'axis',
            axisPointer:{
              type:'line',
              axis:'y',
              z:99
            },
            formatter: formatter
            // 提示框悬浮内容格式器
            // axisPointer: {
            //   type: 'cross',
            //   label: {
            //     formatter: formatter
            //   }}
          },
          // 图例组件
          legend: {
            data: this.timerList,
            y: 'top',
            x: 'right',
            padding: [60, 5, 0, 0],
            // 设置为可滚动的图例
            type: 'scroll',
            orient: 'vertical'
          },
          // 直角坐标系内绘图网格
          grid: {
            left: 50,
            right: 220,
            bottom: 80,
            // 区域是否包含坐标轴的刻度标签
            containLabel: false
          },
          // 工具栏。内置有导出图片，数据视图，动态类型切换，数据区域缩放，重置五个工具。
          toolbox: {
            // 各个工具配置
            feature: {
              // 保存为图片
              saveAsImage: {}
            }
          },
          // grid x轴
          yAxis: {
            splitNumber:0,
            splitLine: {
              show: true
            },
            axisLabel: {
              show: true,
              formatter: function (value, index) {
                return -value + 'm';
              },
            },
            // 坐标轴名称
            min: function (value) {

              return value.min// 向上取整
            },
            max: function (value) {

              return value.max// 向上取整
            },
            name: '孔深(m)',
            // 类型为类目轴适用于离散的类目数据。为该类型时类目数据可自动从 series.data 或 dataset.source 中取，或者可通过 xAxis.data 设置类目数据。
            type: 'value',
            boundaryGap: true,
            // 数据
          },
          xAxis: {
            max: function (value) {
              if (value.max < _this.xNum) {
                return _this.xNum
              }
              return Math.ceil(value.max)// 向上取整
            },
            min: function (value) {
              if (value.min > -_this.xNum) {
                return -_this.xNum
              }
              return Math.ceil(value.min)// 向上取整
            },
            type: 'value',
            name: this.yName,
            nameTextStyle: {
              padding: [0, 0, 0, 20]
            },
          },
          series: this.seriesList
        }
      }
    },

    methods: {
      updateEchart(list, holeDepth = 0,monitorName, colorList, isAutoRecord) {
        const keyMap = {
          AB: 'relativeSynthesis',
          AO: 'relativeA0',
          BO: 'relativeB0',
          X: 'xAngle',
          Y: 'yAngle',
          az: 'az',
          in: 'in'
        }
        const titleMap = {
          AB: '合成方向相对位移',
          AO: 'AO方向相对位移',
          BO: 'BO方向相对位移',
          X: 'X角度',
          Y: 'Y角度',
          az: 'az',
          in: 'in'

        }
        this.monitorName=''
        this.monitorName = titleMap[this.type]
        this.monitorName=monitorName+this.monitorName
        const markLine = {
          data: this.markLine,
          lineStyle: {
            normal: {
              type: 'dashed',
            }, width: 15
          }
        }
        let yList = list[0]?.sbwyDetails?.map(x => -x.depth) || []
        if (isAutoRecord == 3) {
          this.yList = [...yList]
        } else {
          this.yList = [-holeDepth, ...yList]
        }

        let timerList = []
        let seriesList = []
        this.markAreas = {}
        list.map((x, i) => {
          let timer = Format(new Date(x.createTime))
          timerList.push(timer)
          if (colorList !== undefined) {
            let markData = []
            markData = []
            colorList.map(x => {
              //判断显示是岩还是土
              let markDataName
              if (x.lithology == 1) {
                markDataName = '岩质;' + x.remark
              } else {
                markDataName = '土质;' + x.remark
              }
              markData.push([{
                yAxis: -x.startDepth + '',
                name: markDataName,
                label: {
                  show: true,
                  fontSize: 24,
                  position: "insideBottom", // markArea中文字（name）位置
                  // offset: [0, -80], // markArea中文字（name）显示在位置基础上x、y轴偏移
                  color: "rgba(21,21,21,0.64)" // markArea中文字（name）颜色
                },
                itemStyle: {
                  color: x.colorVal + '',
                  opacity: 0.02 //控制颜色
                }
              },
                {yAxis: -x.endDepth + ''}])
            })
            this.markAreas = {//设置具体区域的背景颜色，选择不同区间 设置图表对应的背景颜色
              silent: true,
              data: markData
            }
          }
          let data = [0, ...x.sbwyDetails.map(w => w[keyMap[this.type]])]
          let itemData = []
          this.yList.map((y, index) => {
            itemData.push([data[index], y])
          })
          let item = {
            name: timer,
            splitNumber: 0.5,
            // yAxisIndex: 0, //双y轴设置使用哪个y轴的值
            type: 'line',
            smooth: true,

            label: this.type,
            data: itemData,
            animation: true, // 是否开启动画 默认为true
            addDataAnimation: true,
            markArea: this.markAreas
          }
          if (i === 0) item.markLine = markLine

          seriesList.push(item)
        })
        let markLineData = []
        this.yList.map(x => {
          markLineData.push({
            name: -x,
            yAxis: x
          })
        })
        this.timerList = timerList
        this.seriesList = seriesList
        this.$nextTick(() => {
          this.charts.clear()
          this.charts.resize()
          this.charts.setOption(this.options, true)
        })
      },
      // echart随着窗口改变
      echartResize() {
        this.charts.resize()
      }
    },
    created() {

    },
    mounted() {
      var _this=this
      const Echarts = require('echarts')
      this.charts = Echarts.init(this.$el, null, {locale: 'ZH'})
      this.charts.on('click', params => {
        // 关闭tip提示
        console.log(params)
        this.charts.dispatchAction({type: 'hideTip'})
        params.name= Math.abs(params.data[1])
        this.$emit('showDialog', {params, type: this.type})
      })
      this.charts.on('mouseout', params => {

        // 关闭tip提示
        this.charts.dispatchAction({type: 'hideTip'})
      })
      window.addEventListener('resize', this.echartResize)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.echartResize)
    }
  }
</script>
